package com.example.administrator.liveapp.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.bean.CommodityPayBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.view.FullyLinearLayoutManager;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商城订单支付activity
 */

public class CommodityPayActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout Add_address, add_address;//选择收货地址
    private TextView text_name;//收货人姓名
    private TextView text_phone;//收货人手机号
    private TextView text_detailed_address;//收货人详细地址
    private RecyclerView submitOrders_recycle;//商品订单列表
    private TextView pay_price;//合计金额
    private TextView sum;//小计
    private TextView freight;//邮费
    private ImageView address_icon;//地址图标
    String bookId;//商品ID
    String bookNum;//商品数量
    String freights;//邮费
    String sums;//合计
    String status = "0";
    private CommodityPayBean bean;

    //支付
    private PopupWindow mPopWindow;
    private Button payButton;
    private ImageView zhifubao;
    private ImageView weixin;
    private RelativeLayout zfb;
    private RelativeLayout wx;
    private IWXAPI mIwxapi;
    private TextView moneys;
    private LinearLayout booking_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity_pay);
        initView();
        setData();
    }

    private void initView() {
        Intent intent = getIntent();
        bookId = intent.getStringExtra("bookId");
        bookNum = intent.getStringExtra("bookNum");
        freights = intent.getStringExtra("freights");
        sums = intent.getStringExtra("sum");
        status = intent.getStringExtra("status");
        findViewById(R.id.address_returns).setOnClickListener(this);
        findViewById(R.id.submit_orders).setOnClickListener(this);
        Add_address = (LinearLayout) findViewById(R.id.Add_address);
        add_address = (LinearLayout) findViewById(R.id.add_address);
        address_icon = (ImageView) findViewById(R.id.address_icon);
        add_address.setOnClickListener(this);
        Add_address.setOnClickListener(this);
        sum = (TextView) findViewById(R.id.sum);
        freight = (TextView) findViewById(R.id.freight);
        text_name = (TextView) findViewById(R.id.text_name);
        text_phone = (TextView) findViewById(R.id.text_phone);
        text_detailed_address = (TextView) findViewById(R.id.text_detailed_address);
        submitOrders_recycle = (RecyclerView) findViewById(R.id.submitOrders_recycle);
        pay_price = (TextView) findViewById(R.id.pay_price);
    }

    private void setData() {
        String url = AppUrl.URL + AppUrl.OrderInfoUrl;
        Map<String, String> map = new HashMap<>();
        if (status.equals("0")) {
            map.put("bookNum", bookNum + "-");
            map.put("bookId", bookId + "-");
        } else if (status.equals("1")) {
            map.put("bookNum", bookNum);
            map.put("bookId", bookId);
        }
        map.put("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
        XUtils.Get(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                bean = gson.fromJson(result, CommodityPayBean.class);
                if (!bean.getOrderAddress().getDetailaddress().equals("")) {
                    text_name.setText(bean.getOrderAddress().getNickname());
                    text_phone.setText(bean.getOrderAddress().getTelnumber());
                    text_detailed_address.setText(bean.getOrderAddress().getOrderaddress() + "" + bean.getOrderAddress().getDetailaddress());
                } else {
                    Add_address.setVisibility(View.GONE);
                    address_icon.setVisibility(View.GONE);
                    add_address.setVisibility(View.VISIBLE);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                super.onFinished();
                java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");//精确到小数点后两位
                pay_price.setText("合计¥ :" + sums + "元");
                if (freights.equals("0.00")) {
                    freight.setText("免邮");
                } else {
                    freight.setText("¥ " + freights);
                }
                sum.setText("¥ " + df.format(Double.parseDouble(sums) - Double.parseDouble(freights)));
                FullyLinearLayoutManager linearlayout = new FullyLinearLayoutManager(CommodityPayActivity.this);
                linearlayout.setScrollEnabled(false);
                submitOrders_recycle.setHasFixedSize(true);
                submitOrders_recycle.setLayoutManager(linearlayout);
                OrdersBook book = new OrdersBook(bean.getBook());
                submitOrders_recycle.setAdapter(book);
            }
        });
    }

    class OrdersBook extends RecyclerView.Adapter<CommodityPayActivity.OrdersBook.ViewHolder> {
        public Context context;
        public List<CommodityPayBean.BookBean> book;

        public OrdersBook(List<CommodityPayBean.BookBean> book) {
            this.book = book;
        }


        @Override
        public CommodityPayActivity.OrdersBook.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.ordersbook_item, null);
            CommodityPayActivity.OrdersBook.ViewHolder viewHolder = new CommodityPayActivity.OrdersBook.ViewHolder(view);
            context = parent.getContext();
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Glide.with(context).load(AppUrl.URL + book.get(position).getBookImgUrl()).into(holder.shopping_book_image);
            holder.shopping_book_name.setText(book.get(position).getBookTitle());
            holder.shopping_book_money.setText("¥" + book.get(position).getBookPrice());
            holder.shopping_book_number.setText("×" + book.get(position).getBookNum());
        }

        @Override
        public int getItemCount() {
            return book.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public RoundedImageView shopping_book_image;
            public TextView shopping_book_name;
            public TextView shopping_book_money;
            public TextView shopping_book_number;

            public ViewHolder(View itemView) {
                super(itemView);
                shopping_book_image = (RoundedImageView) itemView.findViewById(R.id.shopping_book_image);
                shopping_book_name = (TextView) itemView.findViewById(R.id.shopping_book_name);
                shopping_book_money = (TextView) itemView.findViewById(R.id.shopping_book_money);
                shopping_book_number = (TextView) itemView.findViewById(R.id.shopping_book_number);
            }
        }
    }

    //    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
//            finish();
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }
    int positions = 0;//区分支付宝支付和微信支付

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.address_returns://退出
                finish();
                break;
            case R.id.submit_orders://提交订单
                if (!text_detailed_address.getText().equals("") && !text_name.getText().equals("")) {
                    showPopupWindow();
                } else {
                    Toast.makeText(this, "请添加收获地址", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.add_address:
                Intent intent = new Intent(this, FillAddress.class);
                intent.putExtra("token", "3");
                startActivityForResult(intent, 1);
                overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                break;
            case R.id.Add_address:
                Intent intent2 = new Intent(this, FillAddress.class);
                intent2.putExtra("addressId", bean.getOrderAddress().getAddressid());
                intent2.putExtra("nickName", bean.getOrderAddress().getNickname());
                intent2.putExtra("telNumber", bean.getOrderAddress().getTelnumber());
                intent2.putExtra("orderAddress", bean.getOrderAddress().getOrderaddress());
                intent2.putExtra("detailAddress", bean.getOrderAddress().getDetailaddress());
                intent2.putExtra("addStatus", bean.getOrderAddress().getAddstatus());
                intent2.putExtra("token", "4");
                startActivityForResult(intent2, 2);
                overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                break;
            case R.id.pay_button://确认支付
                if (positions == 1) {
                    Toast.makeText(this, "支付宝支付正在开发中", Toast.LENGTH_SHORT).show();
                } else if (positions == 0) {
                    if (mPopWindow != null && mPopWindow.isShowing()) {
                        mPopWindow.dismiss();
                    }
                    requestPay();
                }
                break;
            case R.id.zhifubao:
                positions = 1;
                zhifubao.setImageResource(R.drawable.check);
                weixin.setImageResource(R.drawable.no_check);
                break;
            case R.id.weixin:
                positions = 0;
                weixin.setImageResource(R.drawable.check);
                zhifubao.setImageResource(R.drawable.no_check);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            text_name.setText(data.getStringExtra("nickName"));
            text_phone.setText(data.getStringExtra("telNumber"));
            text_detailed_address.setText(data.getStringExtra("detailAddress"));
        } else if (resultCode == RESULT_FIRST_USER) {
            text_name.setText(data.getStringExtra("nickName"));
            text_phone.setText(data.getStringExtra("telNumber"));
            text_detailed_address.setText(data.getStringExtra("detailAddress"));
        }
        Add_address.setVisibility(View.VISIBLE);
        address_icon.setVisibility(View.VISIBLE);
        add_address.setVisibility(View.GONE);

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(CommodityPayActivity.this).inflate(R.layout.appointment_pay_popwindow_page, null);
        mPopWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.trans, null);
        mPopWindow.setBackgroundDrawable(drawable);
        mPopWindow.setOutsideTouchable(true);
        payButton = (Button) contentView.findViewById(R.id.pay_button);
        zhifubao = (ImageView) contentView.findViewById(R.id.zhifubao);
        weixin = (ImageView) contentView.findViewById(R.id.weixin);
        zfb = (RelativeLayout) contentView.findViewById(R.id.zfb);
        wx = (RelativeLayout) contentView.findViewById(R.id.wx);
        moneys = (TextView) contentView.findViewById(R.id.money);
        moneys.setText("¥" + sums);
        zfb.setOnClickListener(this);
        wx.setOnClickListener(this);
        payButton.setOnClickListener(this);
        //设置各个控件的点击响应

        //显示PopupWindow
        View rootview = LayoutInflater.from(CommodityPayActivity.this).inflate(R.layout.activity_commodity_pay, null);
        showPopmenu(rootview);
    }

    private void showPopmenu(View rootview) {
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        // 显示窗口位置
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
    }

    /**
     * 微信支付
     */
    private void requestPay() {
        String url = AppUrl.URL + AppUrl.payUrl;

//        String url = "http://www.banshufang.net/index.php/Subscriber/Wxpay/pay?body=半书房大学&total_fee=1";
        Map<String, String> map = new HashMap<>();
        // 微信
        if (status.equals("0")) {
            map.put("number", bookNum + "-");
            map.put("bookId", bookId + "-");
        } else if (status.equals("1")) {
            map.put("number", bookNum);
            map.put("bookId", bookId);
        }
        map.put("body", "半书房大学");
        map.put("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
        map.put("freight", freights);
        map.put("addressId", bean.getOrderAddress().getAddressid());
        map.put("status", status);
        XUtils.Get(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                JSONObject obj = null;
                try {
                    obj = new JSONObject(result);
                    Log.e("----", result);
                    String message = obj.optString("message");
                    // 微信支付回调
                    setWeChat(obj);
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Toast.makeText(CommodityPayActivity.this, ex.getMessage() + "1", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinished() {
                super.onFinished();
                finish();
            }
        });
    }

    /**
     * 微信支付
     */
    private void setWeChat(JSONObject obj) {
        mIwxapi = WXAPIFactory.createWXAPI(this, obj.optString("appid"));
        mIwxapi.registerApp(obj.optString("appid"));// 将应用注册到微信
        if (mIwxapi != null && mIwxapi.isWXAppInstalled()) {// 判断用户有没有安装微信
            PayReq req = new PayReq();
            req.appId = obj.optString("appid");
            req.partnerId = obj.optString("partnerid");
            req.prepayId = obj.optString("prepayid");
            req.nonceStr = obj.optString("noncestr");
            req.timeStamp = obj.optString("timestamp");
            req.packageValue = obj.optString("package");
            req.sign = obj.optString("sign");
            // req.extData = "app data";// 可选
            mIwxapi.sendReq(req);
        } else {
            Toast.makeText(this, "用户未安装微信", Toast.LENGTH_SHORT).show();
            return;
        }
    }
}
